package com.watson.nettydemo.demo08;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

/**
 * 网络聊天----读写超时---
 *
 * @author: llun
 * @date: 2022/3/11 14:46
 * @version: 1.0
 */
public class WebSocketServer {
    public static void main(String[] args) {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childLoopGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(parentGroup, childLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new LineBasedFrameDecoder(2048));

                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

                            //若在5秒内同时即发生了读又发生了写操作才不会触发all操作空闲事件
                            //若在5秒内读与写操作有任何一项没有发生，都会触发all操作空闲事件
                            pipeline.addLast(new IdleStateHandler(2, 2, 5));

                            pipeline.addLast(new IdeSocketServerHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.bind(6666).sync();
            System.out.println("服务器已启动");
            sync.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            parentGroup.shutdownGracefully();
            childLoopGroup.shutdownGracefully();
        }


    }
}
